package com.ease.dao.statement.factory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.CharSetUtils;

import com.ease.common.util.Detect;
import com.ease.document.freemarker.FreeMarkerUtil;

/**
 * 
 * @author nathanleewei
 * 
 */
public abstract class AbstractFreeMarkerNamedStatementFactory extends Detect implements NamedStatementFactory {

	protected Map<String, String> statements;

	protected void putStatement(String statementName, String statement) {
		if (null == statements) {
			statements = new HashMap<String, String>();
		}
		if (null != statement) {
			statement = trim(removeInvalidHeader(CharSetUtils.delete(statement, "\t\r\n\b")));
		}
		statements.put(statementName, statement);
	}

	protected static String removeInvalidHeader(String string) {
		int value = Character.getNumericValue(string.charAt(0));
		if (value < 0) {
			return removeInvalidHeader(string.substring(1));
		} else {
			return string;
		}
	}

	protected abstract String doGetNamedStatement(String name, Object parameter);

	public String getNamedStatement(String name, Object parameter) {
		String statement = doGetNamedStatement(name, parameter);
		if (null != statement) {// null != parameter &&
			statement = FreeMarkerUtil.processString(statement, parameter);
		}
		return statement;
	}

	protected String transform(String statement) {
		StringBuilder sb = new StringBuilder();

		try {
			BufferedReader bufferedReader = new BufferedReader(new StringReader(statement));

			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				sb.append(line.trim());
				sb.append(" ");
			}

			bufferedReader.close();
		} catch (IOException ioe) {
			return statement;
		}

		return sb.toString();
	}

}
